const _ = require("../import");


/**
 * @api {post} /order/allOrder  allOrder
 * @apiDescription 获取不同状态的订单
 * @apiName allOrder
 * @apiGroup order
 * @apiParam {string} status 查询的订单状态，0：待付款，1：待发货，2：待收货，3：退款/售后，-1：查看所有订单
 * @apiSuccessExample {json} 请求成功的返回:
 *  {
 *      "status" : 200,
 *      "message" : "请求成功"
 *      "result" : "asjXzXxmnSp8TZGWiTSlJF8Gb...5LhYoHs86SEI2LBXrTZ9e/a4frZOWHZ"
 *  }
 * @apiErrorExample {json} 请求失败的返回
 * {
 *   "status": 404,
 *   "message" : "请求失败"
 *   "result": null
 * }
 * @apiSampleRequest http://127.0.0.1:9090/order/allOrder
 * @apiVersion 1.0.0
 */
_.router.post('/allOrder', async function(req, res, next) {

  var status = req.body.status, sql = null, params = [];

  if (status == -1) {
    sql = _.config.sql.getAllOrder
    params = [ _.jwt.decode(req.headers.token).id ]
  } else {
    sql = _.config.sql.getStatusOrder
    params = [ _.jwt.decode(req.headers.token).id, status]
  }


  var allOrder = await _.db.query({
    sql: sql,
    data: params
  });

  if(allOrder.length != 0) {
    res.json({
      status: 200,
      message: '请求成功',
      result: allOrder
    });
  } else {
    res.json({
      status: 200,
      message: '没有订单',
      result: {}
    });
  }

});



/**
 * @api {post} /order/buyOrder  buyOrder
 * @apiDescription submitCar提交订单后，订单页面购买支付后需要用的接口，更改订单状态为待发货
 * @apiName buyOrder
 * @apiGroup order
 * @apiParam {Array} goodsid 订单的goods_id，从allOrder接口中获得。参数格式："[5,6]"
 * @apiSuccessExample {json} 请求成功的返回:
 *  {
 *      "status" : 200,
 *      "message" : "购买成功"
 *      "result" : "asjXzXxmnSp8TZGWiTSlJF8Gb...5LhYoHs86SEI2LBXrTZ9e/a4frZOWHZ"
 *  }
 * @apiErrorExample {json} 请求失败的返回
 * {
 *   "status": 404,
 *   "message" : "购买失败，余额不足"
 *   "result": null
 * }
 * @apiSampleRequest http://127.0.0.1:9090/order/buyOrder
 * @apiVersion 1.0.0
 */
_.router.post('/buyOrder', async function(req, res, next) {

  var goods_id = JSON.parse(req.body.goodsid);

  goods_id.forEach(async function(val) {
    var buyOrder = await _.db.query({
      sql: _.config.sql.buyOrder,
      data: [ 1, val ]
    });
  });

  res.json({
    status: 200,
    message: '购买成功',
    result: {}
  });

});


module.exports = _.router;
